import axios from 'axios'
import { ElMessage } from 'element-plus'
import router from '../router'

const request = axios.create({
  baseURL: '',
  timeout: 5000,
  headers: {
    'Content-Type': 'application/json'
  }
})

// 请求拦截器
request.interceptors.request.use(
  config => {
    // 如果数据是对象，自动转换为JSON字符串
    if (config.data && typeof config.data === 'object') {
      config.data = JSON.stringify(config.data)
    }

    // 添加token到请求头
    const token = localStorage.getItem('token')
    if (token) {
      config.headers['Authorization'] = `Bearer ${token}`
    }

    return config
  },
  error => {
    return Promise.reject(error)
  }
)

request.interceptors.response.use(
  response => response,
  error => {
    if (error.response?.status === 401) {
      localStorage.removeItem('token')
      localStorage.removeItem('isSecondPassword')
      ElMessage.error('未登录或登录已过期')
      router.push('/login')
    }
    return Promise.reject(error)
  }
)

export default request 